import { Component, OnInit, ViewChild } from '@angular/core';
import { HttpRequest } from "../../../service/httpRequest";
import { HideElementService } from "../../../service/hideElement.service";
import { PageModel } from "../../../model/page-model";
import { flyIn } from '../../../animations/fly-in';
import { GlobalVariable } from '../../../global.config';
import { ModalDirective } from 'ng2-bootstrap/modal';

@Component({
  selector: 'app-company',
  templateUrl: './company.component.html',
  styleUrls: ['./company.component.css'],
  animations: [
    flyIn
  ]
})
export class CompanyComponent implements OnInit {
  elc = {a:'公司新增',e:'公司编辑',d:'公司删除'}

  @ViewChild('myModal') public myModal:ModalDirective;
  buttonType:number = 0;
  disabled:string = '';
  model = {name:'',addr:'',short_name:''};
  selectedId:string = '';

  tool = GlobalVariable.tooltip;
  data:any;
  keyword:any;
  pageModel = new PageModel();
  page:number = 1;
  constructor(private httpRequest:HttpRequest,private he:HideElementService) {
    this.elc = this.he.hideElement(this.elc);
  }

  ngOnInit() {
    this.getData();
  }

  getData(){
    this.httpRequest.sendGet('companys/page',{page:this.page}).subscribe(res=>{
      //console.log(res)
      this.data = res.result.aaData;
      this.pageModel.setPage({'iTotalRecords':res.result.iTotalRecords});
    },err=>console.log(err));
  }

  newModal(){
    this.buttonType=1;
    this.model = {name:'',addr:'',short_name:''};
    this.myModal.show();
  }

  confirmNew(){
    this.httpRequest.sendPost('companys',{
      name: this.model.name,
      addr: this.model.addr,
      short_name: this.model.short_name
    }).subscribe(res=>{
      alert("公司创建成功！");
      this.myModal.hide();
      this.disabled='';
      this.getData();
    },err => {alert('公司创建失败!');this.disabled='';console.log(err)});
  }

  editModal(item){
    this.buttonType=2;
    this.selectedId = item.id;
    this.model = {name:item.name,addr:item.addr,short_name:item.short_name};
    this.myModal.show();
  }

  confirmEdit(){
    this.httpRequest.sendPost('companys/'+this.selectedId,{
      name: this.model.name,
      addr: this.model.addr,
      short_name: this.model.short_name
    }).subscribe(res=>{
      alert("公司修改成功！");
      this.myModal.hide();
      this.disabled='';
      this.getData();
    },err => {alert('公司修改失败!');this.disabled='';console.log(err)});
  }

  deleteModal(item){
    this.buttonType = 3;
    this.selectedId = item.id;
    this.model.name = item.name;
    this.myModal.show();
  }

  confirmDelete(){
    this.httpRequest.sendDelete('companys/'+this.selectedId).subscribe(res=>{
      alert("公司删除成功！");
      this.myModal.hide();
      this.disabled='';
      this.getData();
    },err => {alert('公司删除失败!');this.disabled='';console.log(err)});
  }

}
